<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生成订单 - 鲜时蔬</title>
    <!-- 引入Vue.js -->
    <script src="../../js/vue.js"></script>
    <!-- 引入Element UI样式 -->
    <link  type="text/css" rel="stylesheet" href="../../css/index.css">
    <!-- 引入Element UI组件库 -->
    <script src="../../js/index.js"></script>
    <!-- 引入axios -->
    <script src="../../js/axios.min.js"></script>
    <!-- 引入vue-qriously生成二维码 -->
    <script src="../../js/vue-qriously.js"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: "Helvetica Neue", sans-serif; background-color: #f5f5f5; color: #333; }
        .container { width: 1140px; margin: 0 auto; padding: 0 15px; }
        @media (max-width: 1199px) { .container { width: 960px; } }
        @media (max-width: 991px) { .container { width: 720px; } }
        @media (max-width: 767px) { .container { width: 100%; } }

        .header { background: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.1); position: fixed; top: 0; left: 0; right: 0; z-index: 1000; }
        .header-content { display: flex; justify-content: space-between; align-items: center; padding: 15px 0; }
        .logo { display: flex; align-items: center; font-size: 20px; font-weight: bold; color: #27ae60; text-decoration: none; }
        .logo i { margin-right: 8px; }
        .nav { display: flex; }
        .nav a { margin: 0 15px; text-decoration: none; color: #666; font-size: 14px; padding: 5px 0; }
        .nav a.active { color: #27ae60; border-bottom: 2px solid #27ae60; }
        .user-actions { display: flex; align-items: center; }
        .user-actions button { margin-left: 15px; background: none; border: none; color: #666; cursor: pointer; font-size: 14px; display: flex; align-items: center; }
        .user-actions button i { margin-right: 5px; }

        .main { padding-top: 80px; padding-bottom: 50px; }
        .page-title { font-size: 24px; margin-bottom: 20px; }

        .order-content { background: #fff; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px; margin-bottom: 20px; }
        .order-summary { margin-bottom: 30px; padding-bottom: 20px; border-bottom: 1px solid #eee; }
        .summary-title { font-size: 18px; font-weight: bold; margin-bottom: 15px; }
        .order-item { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px dashed #eee; }
        .item-info { flex: 3; }
        .item-price { flex: 1; text-align: right; }

        .order-total { display: flex; justify-content: space-between; font-size: 18px; font-weight: bold; margin: 20px 0; padding-top: 15px; border-top: 1px solid #eee; }
        .total-amount { color: #e74c3c; }

        .pay-button { background-color: #e74c3c; color: white; border: none; border-radius: 4px; padding: 12px 30px; font-size: 16px; cursor: pointer; }
        .pay-button:hover { background-color: #c0392b; }

        .footer { background: #333; color: #fff; padding: 30px 0; margin-top: 50px; }
        .footer-content { text-align: center; font-size: 14px; }

        /* 支付弹框样式 */
        .qrcode-container {
            text-align: center;
            padding: 10px 0;
        }
        .dialog-footer {
            text-align: center;
            margin-top: 20px;
        }
        /* 用户信息下拉菜单 */
        .user-info { position: relative; display: flex; align-items: center; cursor: pointer; }
        .user-avatar { width: 32px; height: 32px; border-radius: 50%; background-color: #27ae60; color: white; display: flex; align-items: center; justify-content: center; margin-right: 8px; font-size: 14px; }
        .user-dropdown { position: absolute; top: 100%; right: 0; background: white; box-shadow: 0 2px 12px rgba(0,0,0,0.1); border-radius: 4px; padding: 5px 0; min-width: 120px; z-index: 10; margin-top: 5px; display: none; }
        .user-dropdown.show { display: block; }
        .user-dropdown-item { padding: 8px 15px; font-size: 14px; color: #606266; cursor: pointer; }
        .user-dropdown-item:hover { background-color: #f5f7fa; color: #27ae60; }
    </style>
</head>
<body>
<div id="app">
    <header class="header">
        <div class="container">
            <div class="header-content">
                <a href="index.html" class="logo">
                    <i class="el-icon-shopping-bag"></i>
                    <span>鲜时蔬</span>
                </a>
                <nav class="nav">
                    <a href="index.html">首页</a>
                    <a href="vegetables.html">蔬菜列表</a>
                    <a href="contact.html">联系我们</a>
                </nav>
                <div class="user-actions">
                    <!-- 根据登录状态显示不同内容 -->
                    <template v-if="isLoggedIn">
                        <div class="user-info" @mouseenter="showDropdown = true" @mouseleave="showDropdown = false">
                            <div class="user-avatar">
                                {{ userInfo.nickName ? userInfo.nickName.charAt(0) : userInfo.userName.charAt(0) }}
                            </div>
                            <span>{{ userInfo.nickName || userInfo.userName }}</span>
                            <div class="user-dropdown" :class="{ 'show': showDropdown }">
                                <div class="user-dropdown-item" @click="goToPersonalCenter">个人中心</div>
                                <div class="user-dropdown-item" @click="logout">退出登录</div>
                            </div>
                        </div>
                    </template>
                    <template v-else>
                        <button @click="goToLogin">
                            <i class="el-icon-user"></i> 登录
                        </button>
                    </template>
                    <button @click="goToCart">
                        <i class="el-icon-shopping-cart"></i> 购物车({{ cartCount }})
                    </button>
                </div>
            </div>
        </div>
    </header>

    <main class="main">
        <div class="container">
            <h2 class="page-title">确认订单</h2>

            <!-- 订单详情展示 -->
            <div class="order-content" v-if="cartData.length > 0">
                <div class="order-summary">
                    <div class="summary-title">订单商品</div>
                    <div class="order-item" v-for="item in cartData" :key="item.productId">
                        <div class="item-info">
                            <div>{{ item.productName }}</div>
                            <div style="font-size: 14px; color: #999;">
                                单价: ¥{{ item.productPrice }} | 数量: {{ item.productCount }}
                            </div>
                        </div>
                        <div class="item-price">
                            ¥{{ (item.productPrice * item.productCount).toFixed(2) }}
                        </div>
                    </div>
                    <div class="order-total">
                        <span>订单总额:</span>
                        <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
                    </div>
                </div>

                <div style="text-align: center;">
                    <button class="pay-button" @click="showPayDialog">确认支付</button>
                </div>
            </div>

            <!-- 空订单提示 -->
            <div v-else>
                <p>订单数据加载失败或为空</p>
                <button class="el-button" @click="goToCart">返回购物车</button>
            </div>
        </div>
    </main>

    <footer class="footer">
        <div class="container">
            <div class="footer-content">
                <p>© 2025 鲜时蔬 版权所有 | 京ICP备12345678号</p>
            </div>
        </div>
    </footer>

    <!-- 支付弹框 -->
    <el-dialog
            title="订单支付"
            :visible.sync="payDialogVisible"
            width="400px"
            :before-close="handleCloseDialog"
            :close-on-click-modal="false">

        <div v-if="loadingOrder">
            <el-loading-spinner><i class="el-icon-loading"></i></el-loading-spinner>
            <p class="el-loading-text">正在创建订单...</p>
        </div>

        <div v-else-if="orderNo">
            <p>订单编号：{{ orderNo }}</p>
            <div v-if="codeUrl" class="qrcode-container">
                <qriously :value="codeUrl" :size="200" />
            </div>
            <p>请使用微信扫描二维码支付</p>
            <p class="qrcode-status" v-if="payStatus">{{ payStatus }}</p>
            <div class="dialog-footer">
                <el-button type="primary" @click="checkPayStatus">查询支付状态</el-button>
            </div>
        </div>

        <div v-else>
            <p>订单创建失败，请重试</p>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                showDropdown: false,
                userInfo: {},
                isLoggedIn: false,
                cartCount: 0,
                orderNo: '',        // 订单编号
                cartData: [],       // 购物车数据
                totalAmount: 0,     // 订单总金额
                codeUrl: '',        // 二维码链接
                timer: null,        // 轮询定时器
                payDialogVisible: false, // 支付弹框显示状态
                loadingOrder: false, // 订单创建加载状态
                payStatus: '等待支付...' // 支付状态提示
            }
        },
        mounted() {
            this.checkLoginStatus();
            // 从URL参数获取购物车数据并展示
            const urlParams = new URLSearchParams(window.location.search);
            const cartDataStr = urlParams.get('cartData');
            if (cartDataStr) {
                this.cartData = JSON.parse(decodeURIComponent(cartDataStr));
                this.calculateTotal();
                this.cartCount = this.cartData.reduce((sum, item) => sum + item.productCount, 0);
            }
        },
        methods: {
            checkLoginStatus() {
                axios.get('/vegetablemarketexpress/user/checkLoginStatus', { withCredentials: true })
                    .then(res => {
                        if (res.data.code === 200 && res.data.data) {
                            this.isLoggedIn = true;
                            this.userInfo = res.data.data;
                        } else {
                            this.isLoggedIn = false;
                            this.$message.warning('请先登录');
                            setTimeout(() => this.goToLogin(), 1000);
                        }
                    });
            },

            // 计算订单总金额
            calculateTotal() {
                this.totalAmount = this.cartData.reduce((sum, item) => {
                    return sum + (item.productPrice * item.productCount);
                }, 0);
            },

            // 显示支付弹框并创建订单
            showPayDialog() {
                this.payDialogVisible = true;
                this.loadingOrder = true;
                this.createOrder();
            },

            // 创建订单
            createOrder() {
                this.orderNo = 'ORD' + new Date().getTime();
                const order = {
                    orderNo: this.orderNo,
                    status: 0, // 0-待支付
                    orderItems: this.cartData.map(item => ({
                        productId: item.productId,
                        productName: item.productName,
                        salePrice: item.productPrice,
                        orderQuantity: item.productCount,
                        amount: item.productPrice * item.productCount,
                    })),
                    totalAmount: this.totalAmount,
                };

                axios.post('/vegetablemarketexpress/order/createOrder', order, { withCredentials: true })
                    .then(res => {
                        if (res.data.code === 200) {
                            this.generateQrCode();
                            this.timer = setInterval(this.checkPayStatus, 3000);
                        } else {
                            this.$message.error('订单创建失败：' + res.data.message);
                            this.loadingOrder = false;
                        }
                    })
                    .catch(err => {
                        console.error('创建订单失败', err);
                        this.$message.error('订单创建异常');
                        this.loadingOrder = false;
                    });
            },

            // 生成支付二维码
            generateQrCode() {
                const order = {
                    orderNo: this.orderNo,
                    totalAmount: this.totalAmount,
                    remark: '订单支付',
                };

                axios.post('/vegetablemarketexpress/order/getNativeCodeUrl', order, { withCredentials: true })
                    .then(res => {
                        this.loadingOrder = false;
                        if (res.data && res.data.code === 200 && res.data.data && res.data.data.code_url) {
                            this.codeUrl = res.data.data.code_url;
                        } else {
                            this.$message.error('生成支付二维码失败：' + (res.data.message || '缺少 code_url'));
                        }
                    })
                    .catch(err => {
                        console.error('生成二维码失败', err);
                        this.$message.error('支付二维码生成异常');
                        this.loadingOrder = false;
                    });
            },

            // 查询支付状态
            checkPayStatus() {
                if (!this.orderNo) return;

                axios.get(`/vegetablemarketexpress/order/getPayStatus/${this.orderNo}`)
                    .then(res => {
                        if (res.data.code === 200) {
                            const payStatus = res.data.data.trade_state;
                            this.payStatus = res.data.data.trade_state_desc || '处理中...';

                            if (payStatus === 'SUCCESS') { // 支付成功
                                clearInterval(this.timer);
                                this.$message.success('支付成功');
                                this.updateOrderStatus();

                                // 2秒后关闭弹框并跳转到购物车
                                setTimeout(() => {
                                    this.payDialogVisible = false;
                                    window.location.href = 'shoppingCart.html';
                                }, 2000);
                            }
                        }
                    })
                    .catch(err => {
                        console.error('查询支付状态失败', err);
                    });
            },

            // 更新订单状态为“已支付”
            updateOrderStatus() {
                const order = {
                    orderNo: this.orderNo,
                };
                axios.post('/vegetablemarketexpress/order/updateStatus', order)
                    .then(res => {
                        if (res.data.code !== 200) {
                            this.$message.warning('订单状态更新失败：' + res.data.message);
                        }
                    })
                    .catch(err => {
                        console.error('更新订单状态失败', err);
                    });
            },

            // 关闭支付弹框的确认
            handleCloseDialog(done) {
                this.$confirm('确认关闭支付窗口？未完成支付的订单将被取消')
                    .then(_ => {
                        done();
                        if (this.timer) {
                            clearInterval(this.timer);
                        }
                    })
                    .catch(_ => {});
            },

            // 页面跳转方法
            goToLogin() { window.location.href = 'login.html'; },
            goToCart() { window.location.href = 'shoppingCart.html'; },
            // 跳转到个人中心
            goToPersonalCenter() {
                this.$message.info('即将跳转到个人中心');
                window.location.href = '/vegetablemarketexpress/html/front/personalCenter.html';
            },
            logout() {
                axios.get('/vegetablemarketexpress/user/logout', { withCredentials: true })
                    .then(() => {
                        this.isLoggedIn = false;
                        this.$message.success('已退出登录');
                        setTimeout(() => this.goToLogin(), 1000);
                    });
            }
        }
    });
</script>
</body>
</html>
